package org.example.cloudnativelab.aspect;

import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.cloudnativelab.annotation.Limiting;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class RateLimitAspect {
    private ConcurrentHashMap<String, RateLimiter> RATE_LIMITER = new ConcurrentHashMap<>();

    @Pointcut("@annotation(org.example.cloudnativelab.annotation.Limiting)")
    public void serviceLimit() {
    }

    @Around("serviceLimit()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Signature sig = point.getSignature();
        MethodSignature msig = (MethodSignature) sig;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        Limiting annotation = currentMethod.getAnnotation(Limiting.class);

        double limitNum = annotation.limitNum();
        String functionName = msig.getName();

        RateLimiter rateLimiter;
        if (RATE_LIMITER.containsKey(functionName)) {
            rateLimiter = RATE_LIMITER.get(functionName);
        } else {
            rateLimiter = RateLimiter.create(limitNum);
            RATE_LIMITER.put(functionName, rateLimiter);
        }
        if (rateLimiter.tryAcquire()) {
            return point.proceed();
        } else {
            return ResponseEntity.status(429).body("Too many requests");
        }
    }

}
